# -*- coding: utf-8 -*-
from flask import jsonify,g,render_template,request
import math
from sqlalchemy.ext.declarative import DeclarativeMeta
import json
import decimal, datetime

def ops_render( template,context = {} ):
    if 'current_user' in  g:
        context['current_user'] = g.current_user
    return render_template( template, **context )

def ops_renderJSON( code = 200,msg = "操作成功~~",data = {} ):
    resp = { "code":code,"msg":msg,"data":data }
    return jsonify( resp )

def ops_renderErrJSON( msg = "系统繁忙，请稍后再试~~",data = {} ):
    return ops_renderJSON( code = -1,msg = msg,data = data )


def iPagenation( params):
    total_count = int( params['total_count'] )
    page_size = int( params['page_size'] )
    page = int( params['page'] )

    total_pages = math.ceil(total_count / page_size)
    total_pages = total_pages if total_pages > 0 else 1

    is_prev = 0 if page <= 1 else 1
    is_next = 0 if page >= total_pages else 1
    pages = {
        'current':page,
        'total_pages':total_pages,
        'total':total_count,
        'page_size':page_size,
        'is_next': is_next,
        'is_prev': is_prev,
        'range': range( 1,total_pages + 1 ),
        'url':params['url']
    }

    return pages

# def page(listdatadone):
#     # 分页
#     req = request.values
#     page = 1
#     if 'p' in req and req['p']:
#         page = int(req['p'])
#
#     page_params = {
#         'total_count': listdatadone.count(),
#         "page_size": 30,
#         'page': page,
#         'url': "/?"
#     }
#     pages = iPagenation(page_params)
#     # 0 - 30,30 - 60 ,60 - 90
#     offset = (page - 1) * page_params['page_size']
#     limit = page * page_params['page_size']
#     listdatadone = listdatadone[offset:limit]
#     return pages,listdatadone

class AlchemyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj.__class__, DeclarativeMeta):
            # an SQLAlchemy class
            fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
                data = obj.__getattribute__(field)
                try:
                    json.dumps(data)  # this will fail on non-encodable values, like other classes
                    fields[field] = data
                except TypeError:  # 添加了对datetime的处理
                    if isinstance(data, datetime.datetime):
                        fields[field] = data.isoformat()
                    elif isinstance(data, datetime.date):
                        fields[field] = data.isoformat()
                    elif isinstance(data, datetime.timedelta):
                        fields[field] = (datetime.datetime.min + data).time().isoformat()
                    else:
                        fields[field] = None
            # a json-encodable dict
            return fields

        return json.JSONEncoder.default(self, obj)